import { Select, SelectProps } from 'antd';
import React from 'react';

/* eslint-disable react/require-default-props */
const Groups: React.FC<{
  searchFunction: Function;
  randerOption: Function;
  onLoadOption: Function;
  onChange?: any;
  value?: any;
}> = ({ searchFunction, randerOption, onLoadOption, onChange, value }) => {
  const [data, setData] = React.useState<SelectProps['options']>([]);
  let isfirst = false;
  React.useEffect(() => {
    if (!isfirst && onLoadOption && value) {
      isfirst = true;
      onLoadOption(value).then(res => {
        setData(res);
      });
    }
  }, [value]);
  const bind = async (newValue: string) => {
    const r = await searchFunction(newValue);
    if (r && r.length > 0) setData(r);
  };

  React.useEffect(() => {
    bind('');
  }, []);

  return (
    <Select
      onChange={onChange}
      filterOption={false}
      value={value}
      allowClear
      showSearch
      placeholder="请输入"
      onSearch={(newValue: string) => {
        bind(newValue);
      }}
      options={(data || []).map(d => randerOption(d))}
    />
  );
};

export default Groups;
